package com.yimi.yinhepda.views.unload_module.palletbind;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.StringUtils;
import com.uce.pda.util.ArrayUtils;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.PalletBindAdapter;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.request.ForkliftDetailVos;
import com.yimi.yinhepda.entity.request.PalletBindCancleRequest;
import com.yimi.yinhepda.entity.request.PalletBindRequest;
import com.yimi.yinhepda.entity.request.QueryPalletUseNumRequest;
import com.yimi.yinhepda.entity.response.QueryLoadDetailChildBillcode;
import com.yimi.yinhepda.entity.response.QueryPalletUseNumResponse;
import com.yimi.yinhepda.entity.response.QueryUnLoadDetailBillcode;
import com.yimi.yinhepda.entity.response.QueryUnloadDetailResponse;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.FastClick;
import com.yimi.yinhepda.utils.ListUtils;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.utils.UcWaybillValidate;
import com.yimi.yinhepda.views.unload_module.UnloadScanActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 托盘绑定界面
 *
 * @author 000432
 */
public class PalletBindActivity extends BaseActivity implements CommonViewHolder.onItemCommonClickListener {

    /**
     * 卸车数据库操作类
     */
    private UnloadScanTableDao mUnloadScanTableDao;
    /**
     * 托盘绑定列表数据
     */
    private RecyclerView rvPalletBindList;
    /**
     * 托盘绑定数据
     */
    private List<QueryUnLoadDetailBillcode> mPalletBindList;
    /**
     * 托盘绑定实体
     */
    private QueryUnLoadDetailBillcode mQueryUnLoadDetailBillcode;
    /**
     * 托盘
     */
    private PalletBindAdapter mAdapter;
    public static Handler mHandler;
    public static final int HANDLER_100 = 100;
    public static final int HANDLER_101 = 101;
    /**
     * 用于保存旧的托盘任务号
     */
    private String mOldForliftNo = "";
    /**
     * 规定托盘数
     */
    private TextView tvProvPalletNum;
    /**
     * 已用托盘数
     */
    private TextView tvUsedPalletNum;
    /**
     * 卸车任务号
     */
    private String mTask;
    /**
     * 卸车任务集合
     */
    private List<UnloadTaskTable> mTaskList;
    /**
     * 1-跨越卸车类型
     */
    private int operType;

    @SuppressLint("HandlerLeak")
    private void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLER_100:
                        Bundle bundle = msg.getData();
                        List<QueryUnLoadDetailBillcode> list = new ArrayList<>();
                        list.addAll((List<QueryUnLoadDetailBillcode>) bundle.getSerializable("palletBindList"));
                        if (mPalletBindList != null) {
                            mPalletBindList.clear();
                        }
                        //按照产品类型排序
                        mPalletBindList.addAll(sortList(list));
                        loadUIAdapter();
                        SoundVibratorManager.playSound(1);
                        break;
                    case HANDLER_101:
                        MyDialog.showAlertDialog(PalletBindActivity.this, "提示", "已超过一个托盘额定绑定票数，请使用托盘绑定！", "确定");
                        SoundVibratorManager.playSound(2);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    public PalletBindActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "托盘绑定界面";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pallet_bind);

        initView();
        initData();
        setHandler();
    }

    public void initView() {
        findViewById(R.id.ib_back).setOnClickListener(this);
        findViewById(R.id.ib_delete).setOnClickListener(this);
        findViewById(R.id.btn_peopleDiff).setOnClickListener(this);
        findViewById(R.id.btn_forkliftDiff).setOnClickListener(this);
        rvPalletBindList = findViewById(R.id.rv_palletBindList);
        tvProvPalletNum = findViewById(R.id.tv_prov_pallet_num);
        tvUsedPalletNum = findViewById(R.id.tv_used_pallet_num);
    }

    private void initData() {
        mUnloadScanTableDao = new UnloadScanTableDao();
        //托盘操作类型
        operType = getIntent().getIntExtra("operType", 0);
        //卸车任务号
        mTask = getIntent().getStringExtra("task");
        mPalletBindList = (List<QueryUnLoadDetailBillcode>) getIntent().getSerializableExtra("palletBindList");
        for (QueryUnLoadDetailBillcode item : mPalletBindList) {
            item.setCheck(false);
        }
        //按照产品类型排序
        mPalletBindList = sortList(mPalletBindList);
        loadUIAdapter();
        //根据任务号查询卸车任务
        mTaskList = new UnloadTaskTableDao().findData(mTask);
        //查询规定托盘数和已用托盘数
        queryPalletNum();
    }

    /**
     * 查询规定托盘数和已用托盘数
     */
    private void queryPalletNum() {
        List<String> stowageList = new ArrayList<>();
        if (mTaskList != null) {
            for (UnloadTaskTable item : mTaskList) {
                stowageList.add(item.getStowageNo());
            }
            QueryPalletUseNumRequest request = new QueryPalletUseNumRequest();
            request.setDeptCode(sharedPreferUtil.getDeptCode());
            request.setStowageNos(stowageList);
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setUrl(Constants.URL_FORKLIFT_USE_NUM)
                    .setRequestObject(request)
                    .setResponsClazz(QueryPalletUseNumResponse.class)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            showToast(msg);
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            QueryPalletUseNumResponse response = (QueryPalletUseNumResponse) obj;
                            if (response != null && response.getData() != null) {
                                QueryPalletUseNumResponse.DataBean data = response.getData();
                                tvProvPalletNum.setText(String.format("规定托盘数：%s", data.getProvideForkNum()));
                                tvUsedPalletNum.setText(String.format("已用托盘数：%s", data.getUsedForkNum()));
                            }
                        }
                    });
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (FastClick.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.ib_back:
                activityBackMethod();
                break;
            case R.id.ib_delete:
                if (mQueryUnLoadDetailBillcode == null || !mQueryUnLoadDetailBillcode.isCheck()) {
                    return;
                }
                //查询扫描的子单是否上传，已上传调用接口撤销，未上传则删除本地托盘数据
                boolean isUpload = false;
                if (mQueryUnLoadDetailBillcode.isCheck()) {
                    for (QueryLoadDetailChildBillcode childEntity : mQueryUnLoadDetailBillcode.getChildList()) {
                        if (childEntity.getPalletBindFlag() == 1) {
                            isUpload =
                                    mUnloadScanTableDao.exitUploadChildWaybillNo(sharedPreferUtil.getValue(Common.USER_CODE), childEntity.getChildWaybillNo(), 2);
                            break;
                        }
                    }
                }
                if (isUpload) {
                    cancleBindRequest();
                } else {
                    deleteLocalData();
                }
                break;
            case R.id.btn_peopleDiff:
                //人工分货
                submitRequest(1);
                break;
            case R.id.btn_forkliftDiff:
                //叉车分货
                submitRequest(2);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            activityBackMethod();
        }
        return false;
    }

    private void activityBackMethod() {
        Bundle bundle = new Bundle();
        bundle.putSerializable("palletBindList", (Serializable) mPalletBindList);
        setResult(UnloadScanActivity.UNLOADSCAN_RESULT_103, this.getIntent().putExtras(bundle));
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler = null;
    }

    @Override
    public void onItemClickListener(int position) {
        if (position == RecyclerView.NO_POSITION) {
            return;
        }
        mQueryUnLoadDetailBillcode = mPalletBindList.get(position);
        if (mQueryUnLoadDetailBillcode.isCheck()) {
            mQueryUnLoadDetailBillcode.setCheck(false);
        } else {
            for (QueryUnLoadDetailBillcode entity : mPalletBindList) {
                entity.setCheck(false);
            }
            mQueryUnLoadDetailBillcode.setCheck(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            doScan(result);
        }
    }

    private void doScan(String result) {

        if (UnloadScanActivity.mHandler != null) {
            //发送消息开始卸车倒计时
            UnloadScanActivity.mHandler.sendEmptyMessage(UnloadScanActivity.HANDLER_104);
        }

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result) && !UcWaybillValidate.validate(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!(" + result + ")");
            return;
        }

        for (QueryUnLoadDetailBillcode entity : mPalletBindList) {
            for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                if (result.equals(childEntity.getChildWaybillNo()) && childEntity.getPalletBindFlag() == 1) {
                    SoundVibratorManager.playSound(2);
                    MyDialog.showAlertDialog(this, "提示", "当前所扫描的标签已扫描，请扫描其它运单！(" + result + ")", "确定");
                    return;
                }
            }
        }

        Bundle bundle = new Bundle();
        bundle.putString("result", result);
        Message msg = new Message();
        msg.what = UnloadScanActivity.HANDLER_100;
        msg.setData(bundle);
        if (UnloadScanActivity.mHandler != null) {
            UnloadScanActivity.mHandler.sendMessage(msg);
        }
    }

    /**
     * 撤销绑定请求
     */
    private void cancleBindRequest() {
        showPgDlg("数据撤销中...");
        PalletBindCancleRequest palletBindCancleRequest = new PalletBindCancleRequest();
        List<PalletBindCancleRequest.ForkliftCancelBindVo> forkliftCancelBindVos = new ArrayList<>();
        for (QueryUnLoadDetailBillcode entity : mPalletBindList) {
            for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                if (childEntity.getPalletBindFlag() == 1) {
                    PalletBindCancleRequest.ForkliftCancelBindVo forkliftCancelBindVo = new PalletBindCancleRequest.ForkliftCancelBindVo();
                    forkliftCancelBindVo.setStowageNo(childEntity.getStowageNo() == null ? entity.getStowageNo() : childEntity.getStowageNo());
                    forkliftCancelBindVo.setChildWaybillNo(childEntity.getChildWaybillNo());
                    forkliftCancelBindVo.setOperTypeCode(2);
                    forkliftCancelBindVos.add(forkliftCancelBindVo);
                }
            }
        }
        palletBindCancleRequest.setForkliftCancelBindVos(forkliftCancelBindVos);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_CANCLE_BIND)
                .setRequestObject(palletBindCancleRequest)
                .setResponsClazz(QueryUnloadDetailResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        deleteLocalData();
                    }
                });
    }

    /**
     * 删除本地已选数据
     */
    private void deleteLocalData() {
        Iterator<QueryUnLoadDetailBillcode> it = mPalletBindList.iterator();
        while (it.hasNext()) {
            QueryUnLoadDetailBillcode entity = it.next();
            if (entity.isCheck()) {
                for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                    if (UnloadScanActivity.stowageNoMap != null) {
                        for (Map.Entry<String, List<QueryUnLoadDetailBillcode>> entry : UnloadScanActivity.stowageNoMap.entrySet()) {
                            for (QueryUnLoadDetailBillcode unLoadDetailBillcode : entry.getValue()) {
                                for (QueryLoadDetailChildBillcode mChildEntity : unLoadDetailBillcode.getChildList()) {
                                    if (childEntity.getChildWaybillNo().equals(mChildEntity.getChildWaybillNo())) {
                                        if (childEntity.getPalletBindFlag() == 1) {
                                            childEntity.setPalletBindFlag(0);
                                            mChildEntity.setPalletBindFlag(0);
                                            LogUtil.e("getChildWaybillNo=" + childEntity.getChildWaybillNo());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                it.remove();
                break;
            }
        }
        if (mQueryUnLoadDetailBillcode != null) {
            mQueryUnLoadDetailBillcode.setCheck(false);
        }
        loadUIAdapter();
        //发送消息重置托盘list
        Bundle bundle = new Bundle();
        bundle.putSerializable("palletBindList", (Serializable) mPalletBindList);
        Message msg = new Message();
        msg.what = UnloadScanActivity.HANDLER_102;
        msg.setData(bundle);
        if (UnloadScanActivity.mHandler != null) {
            UnloadScanActivity.mHandler.sendMessage(msg);
        }
    }

    /**
     * 提交请求
     *
     * @param scanType 分货扫描类型： 1-人工分货 ,2-叉车分货
     */
    private void submitRequest(final int scanType) {
        showPgDlg("正在提交...");
        //绑定票数
        final PalletBindRequest palletBindRequest = new PalletBindRequest();
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                List<ForkliftDetailVos> forkliftDetailVos = new ArrayList<>();
                for (QueryUnLoadDetailBillcode entity : mPalletBindList) {
                    for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                        if (childEntity.getPalletBindFlag() == 1) {
                            ForkliftDetailVos detailVos = new ForkliftDetailVos();
                            detailVos.setWaybillNo(entity.getWaybillNo());
                            detailVos.setChildWaybillNo(childEntity.getChildWaybillNo());
                            detailVos.setAreaCode(entity.getAreaCode());
                            detailVos.setNextDeptCode(entity.getNextDeptCode());
                            detailVos.setNextDept(entity.getNextDeptName());
                            detailVos.setInputType(entity.getInputType());
                            detailVos.setForkliftNo(entity.getForliftNo());
                            detailVos.setScanType(scanType);
                            detailVos.setCancleStatu(entity.getCancleStatu());
                            detailVos.setStowageNo(entity.getStowageNo());
                            detailVos.setOperTime(entity.getOperTime());
                            detailVos.setOperTypeCode(2);
                            detailVos.setBandType(1);
                            detailVos.setType(detailVos.getWaybillNoType());
                            forkliftDetailVos.add(detailVos);
                            //用于保存旧的托盘任务号
                            mOldForliftNo = entity.getForliftNo();
                        }
                    }
                }
                palletBindRequest.setForkliftDetailVos(forkliftDetailVos);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                if (palletBindRequest.getForkliftDetailVos().isEmpty()) {
                    dismissPgDlg();
                    showToast("无扫描数据不可提交！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                        .setUrl(Constants.URL_BIND_FORFLIFT)
                        .setRequestObject(palletBindRequest)
                        .setResponsClazz(QueryUnloadDetailResponse.class)
                        .execute(new UICallBack() {
                            @Override
                            public void onError(String msg) {
                                dismissPgDlg();
                                showToast(msg);
                                SoundVibratorManager.playSound(2);
                            }

                            @Override
                            public void onSuccess(Object obj) {
                                dismissPgDlg();
                                SoundVibratorManager.playSound(1);
                                showToast("绑定成功");
                                //保存旧的托盘任务号
                                sharedPreferUtil.setValue(Common.OLD_FORLIFT_NO, mOldForliftNo);
                                // 重置卸车托盘绑定数据标志为未扫描
                                resetPalletBindData();
                                //清除当前界面数据
                                mPalletBindList.clear();
                                loadUIAdapter();
                                //发送消息刷新数据和重置托盘list和任务号
                                if (UnloadScanActivity.mHandler != null) {
                                    UnloadScanActivity.mHandler.sendEmptyMessage(UnloadScanActivity.HANDLER_101);
                                }
                                //查询规定托盘数和已用托盘数
                                queryPalletNum();
                            }
                        });
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 重置卸车托盘绑定数据标志为未扫描
     */
    private void resetPalletBindData() {
        for (QueryUnLoadDetailBillcode entity : mPalletBindList) {
            for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                if (UnloadScanActivity.stowageNoMap != null) {
                    for (Map.Entry<String, List<QueryUnLoadDetailBillcode>> entry : UnloadScanActivity.stowageNoMap.entrySet()) {
                        for (QueryUnLoadDetailBillcode unLoadDetailBillcode : entry.getValue()) {
                            if(!ArrayUtils.isEmpty(unLoadDetailBillcode.getChildList())){
                                for (QueryLoadDetailChildBillcode mChildEntity : unLoadDetailBillcode.getChildList()) {
                                    if (childEntity.getChildWaybillNo().equals(mChildEntity.getChildWaybillNo())) {
                                        if (childEntity.getPalletBindFlag() == 1) {
                                            childEntity.setPalletBindFlag(0);
                                            mChildEntity.setPalletBindFlag(0);
                                            LogUtil.e("getChildWaybillNo=" + childEntity.getChildWaybillNo());
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void loadUIAdapter() {
        if (mAdapter == null) {
            mAdapter = new PalletBindAdapter(PalletBindActivity.this, mPalletBindList, PalletBindActivity.this);
            rvPalletBindList.setLayoutManager(new LinearLayoutManager(PalletBindActivity.this, LinearLayoutManager.VERTICAL, false));
            rvPalletBindList.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 数据排序
     * 一级排序 红>黄>白>绿,getType
     * 二级排序 时>比>优>串>标
     */
    private List<QueryUnLoadDetailBillcode> sortList(List<QueryUnLoadDetailBillcode> list) {
        for (QueryUnLoadDetailBillcode item : list) {
            //设置二级排序
            item.setSecondSort(Common.setSecondType(item.getProductType(), item.getGoodsPriority(), item.getWaybillNo()));
        }
        String[] sortNameArr = {"secondSort"};
        // true升序,false降序
        boolean[] isAscArr = {true};
        ListUtils.sort(list, sortNameArr, isAscArr);
        return list;
    }
}
